import fs from 'fs';
import profile from '../../profile';

const readline = require('readline');

const readWords = (fileName,delimiter) => {
    return new Promise((res, rej) => {
        //1.按行读取文件内容
        try {
            let filePath = '';
            if(process.env.NODE_ENV === 'development') {
                filePath = `${profile.devWordsPath}/${fileName}`;
            } else {
                filePath = `${profile.proWordsPath}/${fileName}`;
            }
            const read = fs.createReadStream(filePath);
            const objReadline = readline.createInterface({
                input: read,
            });
            let string = '';
            objReadline.on('line', (line) => {
                //2.过滤掉注释内容
                if (line.length !== 0 && !line.startsWith('::') && !line.startsWith('##')) {
                    string += line;
                }
                //3.拼接字串
            });
            objReadline.on('close', () => {
                //4.拆分成数组
                const splitChar = delimiter || ',';
                res(string.split(splitChar));
            });
        } catch (e) {
            rej(e);
        }
    });
};

const readFileSync = (fileName) => {
    try {
        let filePath = '';
        if(process.env.NODE_ENV === 'development') {
            filePath = `${profile.devWordsPath}/${fileName}`;
        } else {
            filePath = `${profile.proWordsPath}/${fileName}`;
        }
        return fs.readFileSync(filePath).toString();
    } catch (err) {
        return '';
    }
};

export default {
    readWords,
    readFileSync,
};

